package com.backstage.discount.controller;


import com.backstage.discount.pojo.MobileEndDiscount;
import com.backstage.discount.pojo.QueryData;
import com.backstage.discount.service.MobileEndDiscountService;
import com.backstage.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 折扣表 前端控制器
 * </p>
 *
 * @author liu-xiang
 * @since 2022-12-13
 */
@RestController
@RequestMapping("/discount")
@CrossOrigin
public class MobileEndDiscountController {
    @Autowired
    private MobileEndDiscountService mobileEndDiscountService;

    /**
     * 模糊分页查询
     *
     * @param queryData 查询条件
     * @return
     */
    @PostMapping("list")
    public R index(@RequestBody QueryData queryData) {
        Page<MobileEndDiscount> page = new Page<>(queryData.getCp(), queryData.getLs());
        QueryWrapper<MobileEndDiscount> wrapper = new QueryWrapper<>();
        if (queryData.getKw() != null) {
            wrapper.like("discountName", queryData.getKw());
        }
        mobileEndDiscountService.page(page, wrapper);
        List<MobileEndDiscount> list = page.getRecords();
        if (!CollectionUtils.isEmpty(list))
            return R.ok().data("items", list).data("total", page.getTotal()).data("current", page.getCurrent())
                    .data("size", page.getSize());
        return R.error();
    }

    /**
     * 根据id删除优惠卷
     *
     * @param id
     * @return
     */
    @GetMapping("remove/{id}")
    public R removeDiscount(@PathVariable String id) {
        return mobileEndDiscountService.removeById(id) ? R.ok() : R.error();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @GetMapping("removes/{ids}")
    public R removesDiscount(@PathVariable List<String> ids) {
        return mobileEndDiscountService.deleteByIds(ids) ? R.ok() : R.error();
    }

    /**
     * 添加优惠劵
     *
     * @param mobileEndDiscount
     * @return
     */
    @PostMapping("add")
    public R addDiscount(@RequestBody MobileEndDiscount mobileEndDiscount) {
        return mobileEndDiscountService.save(mobileEndDiscount) ? R.ok() : R.error();
    }

    /**
     * 根据id查询优惠卷
     *
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    public R getDiscount(@PathVariable String id) {
        MobileEndDiscount mobileEndDiscount = mobileEndDiscountService.getById(id);
        if (mobileEndDiscount != null)
            return R.ok().data("item", mobileEndDiscount);
        return R.error();
    }
}

